package com.hoow.shakoow.shake.adManager

import com.google.android.ads.nativetemplates.TemplateView
import com.google.android.gms.ads.MobileAds
import com.google.android.gms.ads.RequestConfiguration
import com.hoow.shakoow.base.BaseActivity
import java.util.concurrent.atomic.AtomicBoolean

class AdsManager(val activity: BaseActivity) {

    // 初始化标识
    private val isMobileAdsInitializeCalled = AtomicBoolean(false)

    // 状态回调
    private var mAdsStateListener: AdsStateListener? = null

    // reward ad
    private var mRewardedAdManager: RewardedAdManager? = null

    // native ad
    private var mNativeAdManager: NativeAdManager? = null

    /**
     * 初始化
     */
    fun initAdsSdk(listener: AdsStateListener? = null) {
        if (isMobileAdsInitializeCalled.getAndSet(true)) {
            return
        }

        // 设置监听
        mAdsStateListener = listener

        // 初始化 reward ads
        mRewardedAdManager = RewardedAdManager(activity)
        mRewardedAdManager?.setAdsStateListener(listener)

        // 初始化 native ads
        mNativeAdManager = NativeAdManager(activity)

        // 配置测试设备
        val testDeviceIds = listOf("88786D0FBEF9BEFFF6AB52089CD8BA89")
        val configuration = RequestConfiguration.Builder().setTestDeviceIds(testDeviceIds).build()
        MobileAds.setRequestConfiguration(configuration)

        // 初始化 Ads SDK.
        MobileAds.initialize(activity) {
            println("===> MobileAds Ad init completed")
            mAdsStateListener?.onAdsSdkInitCompleted()

            // 预加载广告
            preloadRewardAds()
        }
    }

    /**
     * 预加载 reward ads
     */
    fun preloadRewardAds() {
        mRewardedAdManager?.initAds()
    }

    /**
     * 显示 reward ads
     */
    fun showRewardAds() {
        mRewardedAdManager?.showAds()
    }

    /**
     * 显示 native ads
     */
    fun showNativeAds(templateView: TemplateView) {
        mNativeAdManager?.showAds(templateView)
    }

    /**
     * 设置状态监听
     */
    fun setAdsStateListener(listener: AdsStateListener) {
        mAdsStateListener = listener
    }
}